package com.yuebook.smartrpc.framework.cluster.impl;

import com.google.common.collect.Lists;
import com.yuebook.smartrpc.framework.cluster.ClusterStrategy;
import com.yuebook.smartrpc.framework.model.ProviderService;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.RandomUtils;

/**
 * 加权随机
 * @author honglei
 * @date 2018/11/20 上午10:16
 */
public class WeightRandomClusterStrategyImpl implements ClusterStrategy {

    @Override
    public ProviderService select(List<ProviderService> providerServices) {
        List<ProviderService> list = Lists.newArrayList();
        for (ProviderService service : providerServices) {
            int weight = service.getWeight();
            for (int i=0; i<weight; i++) {
//                list.add(service);
                list.add(service.copy());//为什么要用copy
            }
        }
        int max = list.size();
        int index = RandomUtils.nextInt(0, max);
        return list.get(index);
    }
}
